package com.shop.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shop.constant.Constants;
import com.shop.entity.*;
import com.shop.exception.*;
import com.shop.factory.ObjectFactory;
import com.shop.service.GoodsService;
import com.shop.util.GetMap;
import com.shop.util.PrintJson;
import com.shop.util.ReturnImg;
import com.shop.util.UUIDUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

@WebServlet("/goods/*")
public class GoodsController extends HttpServlet {

    private GoodsService service = (GoodsService) ObjectFactory.getInstance(Constants.GOODS_SERVICE_KEY);

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        if("/shop/goods/add".equals(uri)) {
            clickAddGoods(req,resp);
        }else if("/shop/goods/addgoods".equals(uri)) {
            confirmAddGoods(req,resp);
        }else if("/shop/goods/delete".equals(uri)){
            clickDeleteGoods(req,resp);
        }else if("/shop/goods/update".equals(uri)){
            clickUpdateGoods(req,resp);
        }else if("/shop/goods/updategoods".equals(uri)) {
            confirmUpdateGoods(req,resp);
        }else if("/shop/goods/queryall".equals(uri)) {
            queryAllGoods(req,resp);
        }else if("/shop/goods/queryname".equals(uri)) {
            queryNameGoods(req,resp);
        }else if("/shop/goods/getImg".equals(uri)) {
            getImage(req,resp);
        }else if("/shop/goods/uploadImg".equals(uri)){
            uploadImg(req,resp);
        }else if("/shop/goods/putawaygoods".equals(uri)) {
            putawayGoods(req, resp);
        }else if("/shop/goods/soldgoods".equals(uri)) {
            soldGoods(req, resp);
        }else if("/shop/goods/selectgoods".equals(uri)) {
            selectAllGoods(req, resp);
        }
    }

    private void selectAllGoods(HttpServletRequest req, HttpServletResponse resp) {
        String s_id1 = req.getParameter("s_id");
        int s_id = Integer.parseInt(s_id1);
        Map<String, Object> map = null;
        try {
            List<Goods>  list =  service.selectAllGoods(s_id);
            map = GetMap.getMap(200, "商品查询成功");
            map.put("data",list);
        } catch (DAOException e) {
            e.printStackTrace();
        } catch (GoodListIsNotExistException e) {
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
    }

    private void soldGoods(HttpServletRequest req, HttpServletResponse resp) {
        String g_id1 = req.getParameter("g_id");
        int g_id = Integer.parseInt(g_id1);
        String s_id1 = req.getParameter("s_id");
        int s_id = Integer.parseInt(s_id1);
        Map<String, Object> map = null;
        try {
            service.soldGoods(g_id,s_id);
            map = GetMap.getMap(200, "商品删除成功");
        } catch (DAOException e) {
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
    }

    private void putawayGoods(HttpServletRequest req, HttpServletResponse resp) {
        JSONObject json = PrintJson.paraseJson(req);
        String g_name = json.getString("g_name");
        String g_data = json.getString("g_data");
        String g_datail = json.getString("g_datail");
        Map<String, Object> map = null;
        try {
            Goods goods = new Goods(g_name,g_data,g_datail);
            service.putawayGood(goods);
            map = GetMap.getMap(200, "商品添加成功");
        } catch (DAOException e) {
            e.printStackTrace();
        } catch (GoodsIsNotExistException e) {
            e.printStackTrace();
        }

        PrintJson.printJsonObj(resp,map);

    }

    private void uploadImg(HttpServletRequest req, HttpServletResponse resp) {

        try {
            req.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //获得磁盘文件条目工厂。
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //获取文件上传需要保存的路径，upload文件夹需存在。
        //request.getSession().getServletContext().getRealPath("/upload");
        String path = "d:/img/image/store/goods/";
        //设置暂时存放文件的存储室，这个存储室可以和最终存储文件的文件夹不同。因为当文件很大的话会占用过多内存所以设置存储室。
        factory.setRepository(new File(path));
        //设置缓存的大小，当上传文件的容量超过缓存时，就放到暂时存储室。
        factory.setSizeThreshold(1024*1024);
        //上传处理工具类（高水平API上传处理？）
        ServletFileUpload upload = new ServletFileUpload(factory);

        Map<String,Object> map = null;
        try{
            //调用 parseRequest（request）方法  获得上传文件 FileItem 的集合list 可实现多文件上传。
            List<FileItem> list = (List<FileItem>)upload.parseRequest(req);
            for(FileItem item:list){
                //如果传入的是非简单字符串，而是图片，音频，视频等二进制文件。
                //获取路径名
                String value = item.getName();
                //修改上传图片名。
                String filename = UUIDUtil.getUUID() + value.substring(value.lastIndexOf("."));
                /*第三方提供的方法直接写到文件中。*/
                item.write(new File(path,filename));
                //更新数据库中用户的头像
                map = GetMap.getMap(200,"返回图片路径成功");
                map.put("img_path","d:/img/image/store/goods/"+filename);
                map.put("uu_id",filename);
            }
        }catch(Exception e){
            map = GetMap.getMap(414,"返回图片路径失败");
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
    }

    private void getImage(HttpServletRequest req, HttpServletResponse resp) {
        String img_path = req.getParameter("img_path");

        Map<String,Object> map = null;
        try {
            ReturnImg.returnImg(resp,img_path);
            map = GetMap.getMap(200,"返回头像成功");
        } catch (DAOException e) {
            map = GetMap.getMap(410,"返回头像失败");
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
    }

    private void queryNameGoods(HttpServletRequest req, HttpServletResponse resp) {
        String s_id1 = req.getParameter("s_id");
        int s_id = Integer.parseInt(s_id1);
        String g_name = req.getParameter("g_name");
        Map<String, Object> map = null;
        try {
            List<GoodsListVO>  list =  service.queryAllGoodsLike(s_id,g_name);
            map = GetMap.getMap(200, "商品查询成功");
            map.put("data",list);
        } catch (DAOException e) {
            e.printStackTrace();
        } catch (GoodListIsNotExistException e) {
            e.printStackTrace();
        }

        PrintJson.printJsonObj(resp,map);
    }

    private void queryAllGoods(HttpServletRequest req, HttpServletResponse resp) {
//        JSONObject json = PrintJson.paraseJson(req);
//        String s_id1 = json.getString("s_id");
        String s_id1 = req.getParameter("s_id");
        int s_id = Integer.parseInt(s_id1);
        Map<String, Object> map = null;
        try {
            List<GoodsListVO>  list =  service.queryAllGoods(s_id);
            map = GetMap.getMap(200, "商品查询成功");
            map.put("data",list);
        } catch (DAOException e) {
            e.printStackTrace();
        } catch (GoodListIsNotExistException e) {
            e.printStackTrace();
        }

        PrintJson.printJsonObj(resp,map);
    }

    private void confirmUpdateGoods(HttpServletRequest req, HttpServletResponse resp) {
        JSONObject json = PrintJson.paraseJson(req);
        String gft_id1 = json.getString("gft_id");
        int gft_id = Integer.parseInt(gft_id1);
        String gst_id1 = json.getString("gst_id");
        int gst_id = Integer.parseInt(gst_id1);
        String gtt_id1 = json.getString("gtt_id");
        int gtt_id = Integer.parseInt(gtt_id1);
        String gfour_id1 = json.getString("gfour_id");
        int gfour_id = Integer.parseInt(gfour_id1);
        String g_id1 = json.getString("g_id");
        int g_id = Integer.parseInt(g_id1);
        String img_id1 = json.getString("img_id");
        int img_id = Integer.parseInt(img_id1);
//        String gft_name = json.getString("gft_name");
//        String gst_name = json.getString("gst_name");
//        String gtt_name = json.getString("gtt_name");
        String gfour_name = json.getString("gfour_name");
        String g_name = json.getString("g_name");

        Double gd_price = json.getDouble("gd_price");
        String gd_num1 = json.getString("gd_num");
        int gd_num = Integer.parseInt(gd_num1);
        String img_path = json.getString("img_path");
        String uu_id = json.getString("uu_id");
        UpdateBindData updateBindData = new UpdateBindData(gft_id,gst_id,gtt_id,gfour_id,gfour_name,g_id,g_name,gd_price,gd_num,img_id,img_path,uu_id);
        Map<String, Object> map = null;
        try {
            service.updateGood(updateBindData);
            map = GetMap.getMap(200, "商品修改成功");
        } catch (DAOException e) {
            e.printStackTrace();
        } catch (GoodsIsNotExistException e) {
            e.printStackTrace();
        } catch (GoodDetailIsNotExistException e) {
            e.printStackTrace();
        } catch (ImgIsNotExistException e) {
            e.printStackTrace();
        }

        PrintJson.printJsonObj(resp,map);
    }

    private void clickUpdateGoods(HttpServletRequest req, HttpServletResponse resp) {
        String gd_id1 = req.getParameter("gd_id");
        int gd_id = Integer.parseInt(gd_id1);
        Map<String, Object> map = null;
        try {
            UpdateBindData updateBindData = service.getBackGoods(gd_id);
            map = GetMap.getMap(200, "商品数据绑定成功");
            map.put("data",updateBindData);
        } catch (DAOException e) {
            e.printStackTrace();
        } catch (GoodsIsNotExistException e) {
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);

    }

    private void clickDeleteGoods(HttpServletRequest req, HttpServletResponse resp) {
        String gd_id1 = req.getParameter("gd_id");
        int gd_id = Integer.parseInt(gd_id1);
        Map<String, Object> map = null;
        try {
            service.deleteGood(gd_id);
            map = GetMap.getMap(200, "商品删除成功");
        } catch (DAOException e) {
            e.printStackTrace();
        } catch (ImgIsNotExistException e) {
            e.printStackTrace();
        } catch (GoodDetailIsNotExistException e) {
            e.printStackTrace();
        } catch (GoodsIsNotExistException e) {
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
    }

    private void clickAddGoods(HttpServletRequest req, HttpServletResponse resp) {
        JSONObject json = PrintJson.paraseJson(req);
        //String gft_id1 = req.getParameter("gft_id");
        String gft_name = json.getString("gft_name");
        //String gst_id1 = req.getParameter("gst_id");
        String gst_name = json.getString("gst_name");
        Map<String, Object> map = null;
        try {
            Map<String,Object> typeTotal = service.getBack(gft_name,gst_name);
            map = GetMap.getMap(200, "商品标签拉取成功");
            map.put("data",typeTotal);
        } catch (DAOException e) {
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
    }
    private void confirmAddGoods(HttpServletRequest req, HttpServletResponse resp) {
        JSONObject json = PrintJson.paraseJson(req);
        String gft_name = json.getString("gft_name");
        String gst_name = json.getString("gst_name");
        String gtt_name = json.getString("gtt_name");
        String gfour_name = json.getString("gfour_name");
        String g_name = json.getString("g_name");
        Double gd_price = json.getDouble("gd_price");
        String gd_num1 = json.getString("gd_num");
        int gd_num = Integer.parseInt(gd_num1);
        String img_path = json.getString("img_path");
        String s_id1 = json.getString("s_id");
        int s_id = Integer.parseInt(s_id1);
        String uu_id = json.getString("uu_id");
        Map<String, Object> map = null;
        GoodsDetailImgVO goodsDetailImgVO = new GoodsDetailImgVO(g_name,gft_name,gst_name,gtt_name,gfour_name,gd_price,gd_num,s_id,img_path,uu_id);
        try {
            service.addGood(goodsDetailImgVO);
            map = GetMap.getMap(200, "商品添加成功");
        } catch (DAOException e) {
            e.printStackTrace();
        } catch (GoodsIsNotExistException e) {
            e.printStackTrace();
        } catch (GoodDetailIsExistException e) {
            e.printStackTrace();
        } catch (ImgPathIsExistException e) {
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
    }

}
